﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Reflection;

namespace PmSoft.Core.Job.Timer;

/// <summary>
/// Timer 调度器提供者，实现作业调度逻辑
/// </summary>
public class TimerSchedulerProvider : IJobSchedulerProvider
{
	private readonly IServiceProvider _serviceProvider;
	private readonly ILogger<TimerSchedulerProvider> _logger;
	private readonly List<TimerJobExecutor> _executors = new List<TimerJobExecutor>();

	/// <summary>
	/// 构造函数，注入服务和日志记录器
	/// </summary>
	/// <param name="serviceProvider">服务</param>
	/// <param name="logger">日志记录器</param>
	public TimerSchedulerProvider(IServiceProvider serviceProvider, ILogger<TimerSchedulerProvider> logger)
	{
		_serviceProvider = serviceProvider;
		_logger = logger;
	}

	/// <summary>
	/// 启动调度器并调度所有作业
	/// </summary>
	/// <param name="jobTypes">作业类型的集合</param>
	public async Task StartAsync(IEnumerable<Type> jobTypes)
	{
		foreach (var jobType in jobTypes)
		{
			var jobAttribute = jobType.GetCustomAttribute<JobScheduleAttribute>();
			if (jobAttribute != null && int.TryParse(jobAttribute.Schedule, out int intervalSeconds))
			{
				// 使用 DI 创建 TimerJobExecutor 实例
				var executor = (TimerJobExecutor)ActivatorUtilities.CreateInstance(_serviceProvider, typeof(TimerJobExecutor), jobType);
				executor.Start(intervalSeconds);
				_executors.Add(executor);
				var logger = _serviceProvider.GetRequiredService<ILogger<TimerSchedulerProvider>>();
				logger.LogInformation("作业 {JobName} 已调度，间隔: {IntervalSeconds}秒", jobAttribute.Name, intervalSeconds);
			}
		}
		await Task.CompletedTask;
	}

	/// <summary>
	/// 停止调度器，清理所有定时器
	/// </summary>
	public async Task StopAsync()
	{
		foreach (var executor in _executors)
		{
			executor.Stop();
		}
		_executors.Clear();
		_logger.LogInformation("Timer 调度器已停止");
		await Task.CompletedTask;
	}
}
